<template>
  <el-container id="login">
    <el-main class="main">
      <div class="middle">
        <el-row type="flex" class="row-bg" justify="center" align="middle">
          <el-col :sm="15" :md="8" :lg="5" v-show="type == 'login'">
            <div class="mainForm-title">登&nbsp;录</div>
            <div class="mainForm">
              <el-form
                ref="loginForm"
                label-width="100px"
                label-position="top"
                :model="loginForm"
                :rules="rules"
              >
                <el-form-item label="用户名" prop="username" class="user">
                  <el-input
                    v-model="loginForm.username"
                    auto-complete="off"
                    placeholder="请输入用户名"
                  ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" class="pass">
                  <el-input
                    id="password"
                    type="password"
                    v-model="loginForm.password"
                    auto-complete="off"
                    placeholder="请输入密码"
                    @keyup.enter.native="handleEnterClick"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      width: 100%;
                    "
                  >
                    <el-button
                      id="enterBtn"
                      type="primary"
                      style="width: 100%"
                      @click="submit('loginForm')"
                      >登录</el-button
                    >
                  </div>
                  <div class="bottom">
                    没有账号去<span @click="type = 'register'">注册</span>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col :sm="15" :md="8" :lg="5" v-show="type == 'register'">
            <div class="mainForm-title">注&nbsp;册</div>
            <div class="mainForm">
              <el-form
                ref="registerForm"
                label-width="80px"
                label-position="left"
                :model="registerForm"
                :rules="rules2"
              >
                <el-form-item label="用户名" prop="username" class="user">
                  <el-input
                    size="mini"
                    v-model="registerForm.username"
                    auto-complete="off"
                    placeholder="请输入用户名"
                  ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" class="pass">
                  <el-input
                    id="password"
                    size="mini"
                    type="password"
                    v-model="registerForm.password"
                    auto-complete="off"
                    placeholder="请输入密码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="registerForm.sex">
                    <el-radio label="男"></el-radio>
                    <el-radio label="女"></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" prop="avator">
                  <div v-if="registerForm.avator" class="img-blocks">
                    <div style="position: relative">
                      <img :src="registerForm.avator" style="width: 80px" />
                      <i @click="deleteImg()" class="el-icon-circle-close"></i>
                    </div>
                  </div>
                  <el-upload
                    v-if="!registerForm.avator"
                    class="avatar-uploader"
                    :action="'/api/upload'"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                  >
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                  <el-input
                    type="text"
                    size="mini"
                    v-model="registerForm.phone"
                    auto-complete="off"
                    placeholder="请输入电话"
                  ></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    type="text"
                    size="mini"
                    v-model="registerForm.email"
                    auto-complete="off"
                    placeholder="请输入邮箱"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <el-button
                  id="enterBtn"
                  type="primary"
                  style="width: 100%"
                  @click="register()"
                  >注册</el-button
                >
              </div>
              <div class="bottom">
                已有账号，返回<span @click="type = 'login'">登录</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { login, getJD, getUser, register, addUser } from "../service.js";
import moment from "moment";
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        sex: "男",
        phone: "",
        email: "",
        avator: "",
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
      rules2: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        phone: [{ required: true, message: "电话不能为空", trigger: "blur" }],
        email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        avator: [{ required: true, message: "请上传头像", trigger: "blur" }],
      },
      type: "login",
    };
  },
  beforeCreate() {
    getUser().then((res) => {
      console.log(res);
    });
    getJD().then((res) => {
      console.log(res);
    });
  },
  mounted() {
    // 测试添加景点接口
    // addJD({
    //   jingdianName: 'test',
    //   jingdianDetail: 'test',
    //   jingdianAddress: '111',
    //   jingdianTime: '111',
    //   createdAt: moment().format('YYYY-MM-DD HH:mm:ss'),
    //   updatedAt: moment().format('YYYY-MM-DD HH:mm:ss'),
    // }).then(res => {
    //   console.log(res)
    // })
    // addUser({
    //   username: '123',
    //   sex: '男',
    //   password: '123',
    //   avator: '111',
    //   email: '111',
    //   phone: '111',
    //   admin: '111',
    //   createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    //   updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    // });
  },
  methods: {
    // 密码框 enter 登录
    handleEnterClick() {
      // 获取密码框并让其失焦
      var child = document.getElementById("password").children[0];
      child.blur();
      document.getElementById("enterBtn").click();
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            username: this.loginForm.username,
            password: this.loginForm.password,
          };
          login(params).then((data) => {
            if (data.code === 200) {
              localStorage.setItem(
                "userInfo",
                JSON.stringify({
                  ...data.user,
                  token: "Bearer " + data.token,
                })
              );
              this.$message.success("登录成功！");
              this.$router.push({
                path: "/homepage",
              });
              localStorage.setItem("username", this.loginForm.username);
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    register() {
      this.$refs["registerForm"].validate((valid) => {
        if (valid) {
          let params = this.registerForm;
          console.log({
            ...params,
            createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
            updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
          });
          addUser({
            ...params,
            admin: 'false',
            createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
            updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
          }).then((data) => {
            if (data.code === 200) {
              this.type = "login";
              this.$message.success("注册成功，请登录");
              this.$refs[formName].resetFields();
            } else {
              this.$message.error(data.msg[0].msg);
            }
          });
        }
      });
    },
    handleAvatarSuccess(result) {
      this.registerForm.avator = "http://localhost:3000/" + result.imgName;
      console.log(this.registerForm.avator);
    },
    deleteImg() {
      this.registerForm.avator = "";
    },
  },
};
</script>

<style lang="scss" scoped>
#login {
  background: url("../assets/img/login_bg.png");
  background-repeat: no-repeat;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 100vh;
}
#login .heade {
  padding-top: 15px;
}
#login .headImg {
  position: relative;
  margin-left: 20px;
  margin-top: 20px;
  height: 30px;
  width: 104px;
}
#login .headImg > img {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  vertical-align: middle;
}
#login .middle {
  position: relative;
  top: 50%;
  margin-top: -185px;
}
#login .mainTitle {
  text-align: center;
  font-size: 28px;
  line-height: 32px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 30px;
}
#login .mainForm-title {
  background: #409eff;
  color: #fff;
  height: 48px;
  line-height: 48px;
  text-align: center;
  font-size: 16px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
#login .mainForm {
  padding: 3% 10%;
  background: #ffffff;
  opacity: 0.9;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}
#login .el-form--label-top .el-form-item__label {
  padding: 0 12px 0 0;
}
#login .user.el-form-item.is-required .el-form-item__label:before {
  content: url("../assets/img/user.png");
}
#login .pass.el-form-item.is-required .el-form-item__label:before {
  content: url("../assets/img/pass.png");
}

.back {
  position: absolute;
  top: 15px;
  left: 20px;
  cursor: pointer;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
.bottom {
  font-size: 14px;
  font-weight: 500;
  margin-top: 20px;
  span {
    color: #409eff;
    cursor: pointer;
    font-weight: bold;
    margin-left: 5px;
  }
}
</style>
